#include "mainwindow.h"
#include <QtGui>
#include <QtXml>
#include "savedqueriesdlg.h"
#include "importwidget.h"

#include "ui_about.h"
#include "login.h"
#include "selectbasedlg.h"

MainWindow::MainWindow(UMSDatabase *dbase):QMainWindow()
{
    setupUi(this);

	_slabServer 	= new QLabel();
	_slabUser 		= new QLabel();
	_slabDatabase 	= new QLabel();
	statusBar()->addPermanentWidget(_slabServer);
	statusBar()->addPermanentWidget(_slabUser);
	statusBar()->addPermanentWidget(_slabDatabase);
	statusBar()->setSizeGripEnabled(true);
	connect(actionExecQuery			,SIGNAL(triggered()),SLOT(execQuery()));
	connect(actionLastQuery			,SIGNAL(triggered()),SLOT(savedQueries()));
	connect(actionLoadStructFromFile,SIGNAL(triggered()),SLOT(loadStructFromFile()));
	connect(actionAbout				,SIGNAL(triggered()),SLOT(about()));
	connect(actionAboutQ4			,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
	connect(actionCloseCurrentTab	,SIGNAL(triggered()),SLOT(closeCurrentTab()));
	connect(actionChooseServer		,SIGNAL(triggered()),SLOT(chooseServer()));
	//connect(treeStruct			  	,SIGNAL(doubleClicked(QModelIndex)),SLOT(insertWord(QModelIndex)));	
	connect(actionCreateBD			,SIGNAL(triggered()),SLOT(newStruct()));
	connect(tabWidget				,SIGNAL(tabCloseRequested(int)),SLOT(tabCloseRequested(int)));
	
	setDatabase(dbase);
	
	
	
	//tabWidget->clear();
	
	//createStructModel();
	/*QString fname = QSettings().value("last_file_dbstruct","").toString();
	if(QFile::exists(fname)){
		loadStructFromFile(fname);
	}*/	
	
	//on_actionNewQuery_triggered();	
	//splitter->setSizes(QList<int>() << 0 << 1000);
	
	showMaximized();	
#if QT_VERSION >= 0x040500
	tabWidget->setTabsClosable(true);
#endif
	
	
    QTabBar *tabBar = qFindChild<QTabBar*>(tabWidget);
    if (tabBar) {
        tabBar->installEventFilter(this);		
		checkShowTabBar();
    }
	
	
	
	createMenuDatabase();
	createMenuQueries();
	createMenuUsers();
	createMenuImport();
	
	
	//test1();
	//test2();
}


void MainWindow::test1()
{
	on_actionNewQuery_triggered();
	currentQueryWidget()->loadDatabaseStruct(".ums");
	currentQueryWidget()->insertText("select * from \"umsusers\"");
	currentQueryWidget()->execQuery();
	
}

void MainWindow::test2()
{
	on_actionShowUsers_triggered();
}


void MainWindow::createMenuUsers()
{
	QPushButton *but = pbUsers;
	QMenu *menu = new QMenu();
	menu->addAction(actionShowUsers);
	menu->addAction(actionCreateNewUser);

	but->setMenu(menu);		
}

void MainWindow::createMenuImport()
{
	QPushButton *but = pbImport;
	QMenu *menu = new QMenu();
	menu->addAction(actionImportFromCSV);	
	but->setMenu(menu);		
}


void MainWindow::createMenuQueries()
{
	QPushButton *but = pbQueries;
	QMenu *menu = new QMenu();
	menu->addAction(actionNewQuery);
	menu->addAction(actionLastQuery);
	menu->addAction(actionOpenQuery);
	but->setMenu(menu);	
}

void MainWindow::createMenuDatabase()
{
	QPushButton *but = pbDatabase;
	QMenu *menu = new QMenu();
	//menu->addAction(actionLoadStructFromFile);
	menu->addAction(actionCreateBD);
	menu->addAction(actionLoadStructDB);
	menu->addAction(actionLoadBDProjectFromServer);
	but->setMenu(menu);	
}

void MainWindow::checkShowTabBar()
{
	QTabBar *tabBar = qFindChild<QTabBar*>(tabWidget);
    if (tabBar) {
		if(tabWidget->count()>1) tabBar->show();
		else
			tabBar->hide();
	}
}



bool MainWindow::eventFilter(QObject *object, QEvent *e)
{
    QTabBar *tabBar = qobject_cast<QTabBar*>(object);
    bool mousRel = e->type() == QEvent::MouseButtonRelease;
    bool dblClick = e->type() == QEvent::MouseButtonDblClick;
    if (tabBar && (mousRel || dblClick)) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
        QWidget *tab = tabFromPosition(tabWidget, mouseEvent->pos());
        if (tab && (mouseEvent->button() == Qt::MidButton || dblClick)) {
            tabWidget->removeTab(tabWidget->indexOf(tab));
            //QTimer::singleShot(0, viewer, SLOT(deleteLater()));
            //currentPageChanged(tabWidget->currentIndex());
            return true;
        }
    } 	
    return QWidget::eventFilter(object, e);
}

QWidget* MainWindow::tabFromPosition(const QTabWidget *widget, const QPoint &point)
{
	QTabBar *tabBar = qFindChild<QTabBar*>(widget);
	for (int i = 0; i < tabBar->count(); ++i) {
		if (tabBar->tabRect(i).contains(point))
			return widget->widget(i);
	}
	return 0;
}

void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
	tabWidget->removeTab(index);//removeWidget(currentTab());
}

QueryWidget *MainWindow::on_actionNewQuery_triggered()
{
	QueryWidget *qw = new QueryWidget();
	qw->setDatabase(_dbase);
	int index = tabWidget->addTab(qw,trUtf8("Запрос"));	
	tabWidget->setCurrentIndex(index);
	tabWidget->setTabIcon(index,QIcon(":icons/images/icons/new_query.png"));
	
	
	connect(qw,SIGNAL(queryExecuted()),SLOT(updateStatusBar()));
	checkShowTabBar();
	return qw;
}

StructWidget *MainWindow::newStruct()
{
	StructWidget *w = new StructWidget();
	w->setDatabase(_dbase);
	tabWidget->addTab(w,w->windowTitle());
	tabWidget->setCurrentIndex(tabWidget->count()-1);
	connect(w,SIGNAL(saved()),SLOT(structSaved()));
	connect(w,SIGNAL(openBase(QString)),SLOT(openBase(QString)));
	checkShowTabBar();
	return w;
}

void MainWindow::setDatabase(UMSDatabase *dbase)
{
	_dbase = dbase;
	updateStatusBar();
}

void MainWindow::updateStatusBar()
{
	_slabServer->setText(trUtf8("Сервер:")+_dbase->server());
	_slabUser->setText(trUtf8("Пользователь:")+_dbase->user());
	if(!_dbase->lastDatabase().isEmpty())
		_slabDatabase->setText(trUtf8("База данных:")+_dbase->lastDatabase());
}

void MainWindow::execQuery()
{
	if(currentQueryWidget()==0) return;
	currentQueryWidget()->execQuery();
	updateStatusBar();
}

void MainWindow::savedQueries()
{
	SavedQueriesDlg dlg;
	if(dlg.exec()){
		on_actionNewQuery_triggered();
		if(!currentQueryWidget()) return;

		currentQueryWidget()->setQuery(dlg.query);
	}
}

QWidget *MainWindow::currentTab()
{
	return tabWidget->currentWidget();
}

QueryWidget *MainWindow::currentQueryWidget()
{
	return qobject_cast<QueryWidget*>(currentTab());
}

void MainWindow::loadStructFromFile()
{
	QSettings sets;
	QString fname = QFileDialog::getOpenFileName(this,trUtf8("Выберите файл со структурой базы данных"),sets.value("last_file_dbstruct","").toString(),tr("XML (*.xml)"));
	if(!fname.isEmpty()){
		sets.setValue("last_file_dbstruct",fname);		
		loadStructFromFile(fname);
	}
}

void MainWindow::loadStructFromFile(const QString &fname)
{
	if(!currentQueryWidget()) return;
	QFile file(fname);
	if(!file.open(QIODevice::ReadOnly)){
		QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Ошибка открытия файла %1").arg(file.fileName()));
		return;
	}
	QDomDocument doc;
	doc.setContent(&file);
	currentQueryWidget()->loadStruct(doc);
	file.close();
}

int MainWindow::userWidgetIndexByUserName(const QString &username)
{
	for(int i=0;i<tabWidget->count();i++){
		UserWidget *w =  qobject_cast<UserWidget*>(tabWidget->widget(i));
		if(w && w->user()==username){			
			return i;
		}
	}
	return -1;
}

void MainWindow::showUserWidget(const QString &username)
{	
	UserWidget *w = new UserWidget(_dbase);
	//w->setUserNode(userNode(username));
	//qw->setDatabase(_dbase);
	int index = tabWidget->addTab(w,trUtf8("Пользователи"));
	tabWidget->setCurrentIndex(index);
	tabWidget->setTabIcon(index,QIcon(":icons/images/icons/user.png"));
	//connect(w,SIGNAL(saved(QString,QDomElement)),SLOT(userSaved(QString,QDomElement)));
	checkShowTabBar();
}



void MainWindow::about()
{
	QDialog dlg;
	Ui::formAbout ui;
	ui.setupUi(&dlg);
	dlg.exec();
}

void MainWindow::closeCurrentTab()
{
	if(!currentTab()) return;
	tabWidget->removeTab(tabWidget->currentIndex());//removeWidget(currentTab());
}

void MainWindow::chooseServer()
{
	Login log;
	if(log.exec()){
		setDatabase(log.dbase);
	}
}


void MainWindow::on_actionLoadStructDB_triggered()
{
	//StructWidget *sw = static_cast<StructWidget*>(currentTab());
	QSettings sets;
	QString fname = QFileDialog::getOpenFileName(this,trUtf8("Выберите файл с проектом структуры базы данных"),sets.value("last_file_project_dbstruct","").toString(),STRUCT_PROJ_FILENAME_FILTER);
	if(fname.isEmpty()) return;
		
	sets.setValue("last_file_project_dbstruct",fname);		

	newStruct();	
	StructWidget *sw = static_cast<StructWidget*>(currentTab());
	if(!sw){
		qWarning() << Q_FUNC_INFO << "current StructWidget is null";
		return;
	}
	
	sw->loadFromFile(fname);
	setTabTextForStruct(sw);	
}

void MainWindow::setTabTextForStruct(StructWidget *sw)
{
	if(!sw) return;
	tabWidget->setTabText(tabWidget->indexOf(sw),trUtf8("Проект: \"%1\"").arg(sw->databaseAlias()));
}

void MainWindow::structSaved()
{
	setTabTextForStruct(static_cast<StructWidget*>(sender()));
}


UserWidget *MainWindow::currentUserWidget()
{
	UserWidget *uw=0;
	for(int i=0;i<tabWidget->count();i++){
		uw = qobject_cast<UserWidget*>(tabWidget->widget(i));
		if(uw) break;
	}
	return uw;
}

void MainWindow::on_actionLoadUsersFromFile_triggered()
{
	if(!currentUserWidget()){
		on_actionShowUsers_triggered();
	}
	if(!currentUserWidget()) return;
	QSettings sets;
	QString fname = QFileDialog::getOpenFileName(this,trUtf8("Выберите файл со пользователями базы данных"),sets.value("last_file_dbusers","").toString(),tr("XML (*.xml)"));
	if(!fname.isEmpty()){
		sets.setValue("last_file_dbusers",fname);		
		currentUserWidget()->loadUsersFromFile(fname);
	}
}





void MainWindow::on_actionCreateNewUser_triggered()
{
	if(!currentUserWidget()){
		on_actionShowUsers_triggered();
	}
	if(!currentUserWidget()) return;
	QSettings sets;
	QString fname = sets.value("last_file_dbusers","").toString();		
	if(QFile::exists(fname)){
		currentUserWidget()->loadUsersFromFile(fname);
	}
	currentUserWidget()->createNewUser();

	//appendUserToTree("username");
}

void MainWindow::userSaved(QString oldname,QDomElement elem)
{
/*	for(int i=0;i<_itemUsers->rowCount();i++){
		if(_itemUsers->child(i)->text()==oldname){
			QString username = nodeValue("name",elem);			
			_itemUsers->child(i)->setText(username);
			tabWidget->setTabText(userWidgetIndexByUserName(username),trUtf8("Пользователь:")+username);
			
			QDomElement root = _docUsers.firstChildElement("ums");
			root.replaceChild(elem,userNode(oldname));
			//qDebug() << _docUsers.toString().toUtf8();
			QFile file(_userFileName);
			if(file.open(QIODevice::WriteOnly)){
				file.write(_docUsers.toString().toUtf8());
			}
			file.close();
			break;
		}
	}*/
}

void MainWindow::on_actionImportFromCSV_triggered()
{
	ImportWidget *w = new ImportWidget();
	//w->setUserNode(userNode(username));
	w->setDatabase(_dbase);
	tabWidget->addTab(w,trUtf8("Импорт"));
	tabWidget->setCurrentIndex(tabWidget->count()-1);
	w->selectFile();
	connect(w,SIGNAL(openQueryWindow(QString)),SLOT(openQueryWindow(QString)));
	checkShowTabBar();
	//connect(w,SIGNAL(saved(QString,QDomElement)),SLOT(userSaved(QString,QDomElement)));
}

void MainWindow::openQueryWindow(const QString &query)
{
	QueryWidget *qw = on_actionNewQuery_triggered();
	if(qw) qw->setQuery(query);
}

void MainWindow::openBase(const QString &dbname)
{
	QueryWidget *qw = on_actionNewQuery_triggered();
	if(qw) qw->loadDatabaseStruct(dbname);
	
/*	
	cboxDBName->setEditText(dbname);
	on_pbSelectDatabase_clicked();
*/
}


void MainWindow::tabCloseRequested(int)
{
	checkShowTabBar();
}


FirstTabWidget::FirstTabWidget(QWidget *p):QTabWidget(p)
{
	
}

void FirstTabWidget::removeTab(int index)
{
	//qDebug() << Q_FUNC_INFO << index;
	if(index!=0){
		QTabWidget::removeTab(index);
	}
	else{
		QMessageBox::warning(this,trUtf8("Внимание"),trUtf8("Простите, но эту вкладку закрыть нельзя."));
	}
}

void MainWindow::on_actionShowUsers_triggered()
{
	showUserWidget(trUtf8("Пользователи"));
}

void MainWindow::on_actionLoadBDProjectFromServer_triggered()
{
	SelectBaseDlg sdb;
	if(sdb.exec()){
		StructWidget *sw = newStruct();
		if(sw!=0){
			sw->loadFromServer(sdb.databaseName());
		}
	}
}

void MainWindow::on_actionOpenQuery_triggered()
{
	QSettings sets;
	QString fname = QFileDialog::getOpenFileName(this,trUtf8("Выберите файл с запросами"),sets.value("last_file_query","").toString(),tr("MQL (*.mql)"));
	if(!fname.isEmpty()){
		sets.setValue("last_file_query",fname);
		QFile file(fname);
		if(!file.open(QIODevice::ReadOnly)){
			QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Ошибка при открытии файла '%1'").arg(file.fileName()));
			return;
		}
		QString queries = QString::fromUtf8(file.readAll());
		file.close();
		
		QueryWidget *qw = currentQueryWidget();
		if(!qw) qw = on_actionNewQuery_triggered();
			
		
		qw->setQuery(queries);
	}	
}
